import React, { Component } from "react";
import { countdownAction } from "../../Redux/Action/countdownAction/countdownAction";
import { connect } from "react-redux";

import "./countdown.scss";

const SECONDS = 60;

class Countdown extends Component {
	constructor(props) {
		super(props);

		this.state = {
			status: props.params.status, // 倒计时按钮状态( disable:不可发送, able:可发送, sending:倒计时中)
			nums: props.params.nums || SECONDS, // 倒计时时间（s）
			tips: "", // 提示信息
			countdown: "发送验证码" // 倒计时按钮值
		};
	}

	componentWillUnmount() {
		clearInterval(this.clock);
		sessionStorage.setItem("time", this.state.nums);
	}

	componentDidMount() {
		this.handleSend("init");
	}

	// 点击发送验证码
	handleSend(type) {
		switch (this.state.status) {
			case "able": // 按钮处于可发送状态发送并倒计时
				if (type !== "init") {
					this.props.params.callback(type);
				}
				// 倒计时开启
				this.clock = setInterval(() => this.doLoop(), 1000);
				// 状态改变
				this.setState({
					status: "sending",
					countdown: "重新发送(" + this.state.nums + "s)"
				});
				// // 发送请求
				// if (!sessionStorage.getItem('time') || sessionStorage.getItem('time') === 60)
				// 	this.props.params.sendCode();
				break;
			case "disable": // 按钮处于不可点击状态，点击后提示
				break;
			case "sending": // 按钮处发送状态，点击后提示
				break;
			default:
				break;
		}
		// 通知父组件

		this.setState({
			tips: this.props.params.sendingClick
		});
	}

	// 倒计时实现
	doLoop() {
		let nums = this.state.nums;
		nums--;
		this.setState({
			nums: nums
		});
		if (nums > 0) {
			this.setState({
				countdown: "重新发送(" + nums + "s)"
			});
		} else {
			this.resetButton();
		}
	}

	// 按钮重置
	resetButton() {
		sessionStorage.removeItem("time");
		clearInterval(this.clock); // 清除js定时器
		this.setState({
			countdown: "重新获取",
			status: "able",
			nums: SECONDS // 重置时间
		});
		// 通知父组件
		// this.props.params.callback(false, 'able');
	}

	render() {
		return (
			<div
				id="sendCode"
				ref="sendCode"
				className={"input-group-addon send_" + this.state.status}
				onClick={() => this.handleSend()}
			>
				{this.state.countdown}
			</div>
		);
	}
}

//需要渲染什么数据
function mapStateToProps(state) {
	return state;
}

//需要触发什么行为
function mapDispatchToProps(dispatch) {
	return {
		_timeInfo: time => dispatch(countdownAction(time))
	};
}

const CountdownPage = connect(mapStateToProps, mapDispatchToProps)(Countdown);
export default CountdownPage;
